<template>
  <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option
          v-for="item in list"
          :key="item.id"

          :label="item.username"
          :value="item.username"
        />

      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { getemployeesSimple } from '@/api/employees'
//
import { getDepartment, putDepartment } from '@/api/departments.js'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    const validateCCode = (rules, value, callback) => {
      //

      let codeList = this.originList.map((item) => item.code)
      // codeList.includes(()=>{})
      console.log('validateCCode', codeList)
      if (codeList.includes(value)) {
        callback(new Error('code已存在'))

        //
        if (this.isEdit) {
          codeList = this.originList.filter((item) => item.id !== this.id).map((item) => item.code)
        }
      } else {
        callback()
      }
    }
    const validateName = (rules, value, callback) => {
      //

      let codeList = this.originList.filter((item) => item.pid === this.id).map((item) => item.name)

      if (this.isEdit) {
        //
        const pid = this.originList.find(item => item.pid === this.id).pid

        //
        codeList = this.originList.filter(item => item.pid === pid).filter(item => item.id !== this.id).map(item => item.name)
      }
      if (codeList.includes(value)) {
        callback(new Error(`name${value}名称已存在`))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      //
      rules: {
        name: [{ required: true, message: '请输入部门', triggr: 'blur' }, { min: 1, max: 10, message: '请输入1到10位的长度', triggr: 'blur' }, {
          validator: validateName, triggr: 'blur'
        }],
        code: [{ required: true, message: '请输入编码', triggr: 'blur' }, { min: 1, max: 10, message: '请输入1到10位的长度', triggr: 'blur' }, {
          validator: validateCCode, triggr: 'blur'
        }],
        manager: [{ required: true, message: '请输入负责人', triggr: 'blur' }],
        introduce: [{ required: true, message: '请输入信息', triggr: 'blur' }, { min: 1, max: 300, message: '请输入1到300位的长度', triggr: 'blur' }]
      },
      list: []
    }
  },

  // 监听器
  watch: {
    // id: function(new_value, old_value) {
    //   this.loadDepartment()
    // }

    id: {
      handler: function(new_value, old_value) {
        if (this.isEdit) {
          this.loadDepartment()
        }
      }
      // immediate: true

    }
  },
  created() {
    this.loadEmployeesSimple()
    if (this.isEdit) {
      this.loadDepartment()
    }
  },
  methods: {
    hreset() {
      this.$refs.deptForm.resetFileds()
    },

    // 获取部门详情
    async loadDepartment() {
      try {
        const res = await getDepartment(this.id)
        console.log(res)
        this.form = res.data
      } catch (error) {
        console.log(error)
      }
    },

    //
    async loadEmployeesSimple() {
      try {
        const res = await getemployeesSimple()
        console.log(res)
        this.list = res.data
      } catch (error) {
        console.log(error)
      }
    },

    async doAdd() {
      try {
        // 2. 调用接口
        const res = await putDepartment({ ... this.id, ...this.form })
        console.log(res)

        this.$emit('success')
      } catch (error) {
        console.log(error
        )
      }
      // 去获取pid： 当前要添加的部门所在的父级的id
      // 从props中获取
      // 1. 组装参数

      // 3. 通知父组件：关闭弹层，再次更新数据
      // this.$emit('success')
    },

    // 编辑部门
    async dohEid() {
      try {
        console.log(2)
        // 2. 调用接口
        const res = await putDepartment(this.form)
        console.log(3)
        console.log('dohEid', res)
        //
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 关闭弹框
        // 重新渲染
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 确定
    hSubmit() {
      // 兜底
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return // 失败
        this.isEdit ? this.dohEid() : this.doAdd()
      })
    },
    // 取消
    hCancel() {
      this.$emit('close')
    }
  }
}
</script>
